import logging
import threading
import cv2
import RPi.GPIO as GPIO
import os
import time
from pathlib import Path
from ConfigClass import ConfigClass

lock = threading.Lock()


class VideoSave:
    def __init__(self, config):
        # 配置器
        self.config = config
        # --------------------------------------------------
        # 启动触发器
        self.setup()
        # 照片的存放
        self.runFlagTimes = 40
        self.indexJpg = 0

        # 增加照片目录
        timestr = time.strftime("%Y%m%d", time.localtime())
        self.dirStr = "./img/" + timestr + "/"
        my_path = Path(self.dirStr)
        if not my_path.exists():
            os.makedirs(self.dirStr)
        # 增加日志处理
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.INFO)
        logfileName = time.strftime("%Y%m%d", time.localtime())
        logfileName = logfileName + "_videoSave_log.txt"
        fh = logging.FileHandler(logfileName, mode='w')
        fh.setFormatter(logging.Formatter("[%(asctime)s]:%(levelname)s:%(message)s"))
        self.logger.addHandler(fh)

    def setup(self):
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.add_event_detect(17, GPIO.BOTH, callback=self.detect)

    def detect(self, chn):
        global lock
        x = GPIO.input(17)
        if x == 0:  # 没有东西
            pass
        if x == 1:  # 有东西
            lock.acquire()
            self.runFlagTimes = 40
            lock.release()

    def video_capture_func(self):
        global lock
        cap1 = cv2.VideoCapture(0)
        while True:
            try:
                ret, frame_read_t = cap1.read()
                if not ret:
                    # 视频捕获异常  errorUrl?videoID=
                    # url = self.config.errorUrl + "?videoID=" + str(self.config.videoAID)
                    # self.logger.info("视频捕获error")
                    # self.MsgList.append(url)
                    continue
                lock.acquire()
                if self.runFlagTimes > 0:
                    self.runFlagTimes = self.runFlagTimes - 1
                    # 这里正常存取照片
                    frame_read = frame_read_t[self.config.cut_top:self.config.cut_bottom,
                                 self.config.cut_left:self.config.cut_right]

                    str_jpg = self.dirStr + "{:0>9d}.jpg"
                    str_jpg = str_jpg.format(self.indexJpg)
                    cv2.imwrite(str_jpg, frame_read)
                    self.indexJpg += 1

                lock.release()

            except Exception as e:
                if len(str(e)) != 0 and str(e).isspace() is not True:
                    errorMsg = "video_capture_func error={0}".format(e)
                    self.logger.info(errorMsg)


if __name__ == '__main__':
    con_fig = ConfigClass()
    video_capture = VideoSave(con_fig)
    # 启动获取照片主线程
    video_capture.video_capture_func()
